package com.bfxy.rabbit.api;

import com.bfxy.rabbit.api.exception.MessageRuntimeException;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author caryguan 建造者模式
 * @version V1.0
 * @Package com.bfxy.rabbit.api
 * @date 2020/9/30 17:44
 */
public class MessageBuilder {

    /**
     * 消息的唯一ID
     */
    private String messageId;

    /**
     * 消息的主题,exchange我们已经选择为topic
     */
    private String topic;

    /**
     * 消息的路由规则,topic主题耦合的属性
     */
    private String routingKey = "";

    /**
     * 消息附加属性
     */
    private Map<String, Object> attributes = new HashMap<>();

    /**
     * 延迟消息的参数配置,只有延迟消息才会用到这个属性,其他为0
     */
    private int delayMills;

    /**
     * 消息类型
     */
    private String messageType = MessageType.CONFIRM;

    /**
     * 构造函数私有化
     */
    private MessageBuilder() {

    }

    /**
     * 获取私有化的对象,和上面构造方法整合就相当于这是一个懒汉单例
     */
    public static MessageBuilder create() {
        return new MessageBuilder();
    }

    public MessageBuilder withMessageId(String messageId) {
        this.messageId = messageId;
        return this;
    }

    public MessageBuilder withTopic(String topic) {
        this.topic = topic;
        return this;
    }

    public MessageBuilder withRoutingKey(String routingKey) {
        this.routingKey = routingKey;
        return this;
    }

    public MessageBuilder withAttributes(Map<String, Object> attributes) {
        this.attributes = attributes;
        return this;
    }

    /**
     * 这里和上面的有区分,添加map属性
     *
     * @param key
     * @param value
     * @return
     */
    public MessageBuilder withAttribute(String key, Object value) {
        this.attributes.put(key, value);
        return this;
    }

    public MessageBuilder withDelayMills(int delayMills) {
        this.delayMills = delayMills;
        return this;
    }

    public MessageBuilder withMessageType(String messageType) {
        this.messageType = messageType;
        return this;
    }

    /**
     * 返回建造者本身的方法
     */
    public Message build() {
        /**
         * 做自定义的判断,条件不足不建造
         *
         */
        if (messageId == null) {
            messageId = UUID.randomUUID().toString();
        }
        //程序运行时才会发现topic为null,编译器不会发现,我们确立一个运行时异常
        if (topic == null) {
            throw new MessageRuntimeException("this topic is null!!");
        }
        Message message = new Message(messageId, topic, routingKey, attributes, delayMills, messageType);
        return message;
    }
}